package com.bootdo.api;

import com.bootdo.backlist.dto.AppuserDTO;
import com.bootdo.backlist.form.NoteCodeForm;
import com.bootdo.backlist.service.AppuserService;
import com.bootdo.backlist.service.YunPianService;
import com.bootdo.common.enums.ResultEnum;
import com.bootdo.common.interfaces.Add;
import com.bootdo.common.interfaces.Update;
import com.bootdo.common.utils.AccountValidatorUtil;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信验证码接口
 * @author Zengcx
 * @date 2019-04-16 08:46
 */
@Slf4j
@RestController
@RequestMapping("/api/yunpian")
public class ApiYunPianController {

    @Autowired
    private YunPianService yunPianService;

    @Autowired
    private AppuserService appuserService;

    /**
     * 获取验证码
     * @return
     */
    @PostMapping("/getCode")
    public R getCode(@Validated(Add.class)NoteCodeForm noteCodeForm, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            log.error("【参数错误】noteCodeForm={}",noteCodeForm);
            return R.error(bindingResult.getFieldError().getDefaultMessage());
        }
        if (!AccountValidatorUtil.isMobile(noteCodeForm.getPhone())){
            return R.error("请输入正确的手机号");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("phone",noteCodeForm.getPhone());
        List<AppuserDTO> dtoList = appuserService.list(map);
        if (noteCodeForm.getCodeType() == 1){
            if (!CollectionUtils.isEmpty(dtoList)){
                return R.error(ResultEnum.PHONE_USE_REGISTER.getMessage());
            }
        }else if (noteCodeForm.getCodeType() == 2){
            if (CollectionUtils.isEmpty(dtoList)){
                return R.error(ResultEnum.PHONE_NOT_REGISTER.getMessage());
            }
        }else {
            return R.error(ResultEnum.PARAM_ERROR.getMessage());
        }

        return yunPianService.getCode(noteCodeForm);
    }

}
